<?php
class ApiPlayerController extends ApiController
{
  public $allows = ['login'];

  public function loginAction()
  {
    $resp = $this->getModel('miniprogram')->jscode2session($this->req->getPostTrim('code'));
    if ($resp->errcode ?? false) {
      return $this->errorReturn($resp->errmsg);
    }
    // $resp = (object) [ 'openid' => 'o2uaZ5RS-ISQSTMoQdS3u2JoHwwQ'];
    $playerModel = $this->getModel('player');
    if (!($player = $playerModel->getPlayer($resp->openid, 'players.openid'))) {
      $player = $playerModel->createPlayer([
       'openid' => $resp->openid
      ]);
    }
    if ($player && $player->login()) {
      $this->account = $player;
      //查询距离上次登陆的时获取鲜花的总送
      return $this->okReturn([
        'resp' => $resp,
        'incomes' => $player->getItemFlowersIncomes()
      ]);
    }
    return $this->errorReturn('创建玩家失败，请重试');
  }

  public function contactAction()
  {
    if ($this->req->isPost()) {
      $phone = $this->req->getPostTrim('phone');
      $address = $this->req->getPostTrim('address');
      $isopengift = $this->req->getPostTrim('isopengift') == '1';
      $gitfresult = false;
      $realname = $this->req->getPostTrim('realname');
      if (empty($phone) || !is_phone($phone)) {
        return $this->errorReturn('请填写正确手机号');
      } else if (empty($realname)) {
        return $this->errorReturn('请填写用户名');
      } else if (empty($address)) {
        return $this->errorReturn('请填写用户地址');
      }
      //检查手机号是否已经存在
      if ($this->getModel('mysql')->query('select count(*) from `players` where `phone` = ?', [ $phone ])->field()) {
        return $this->errorReturn('该手机号已经领取过！！');
      }

      if ($isopengift) {
        $count = $this->getModel('mysql')->query('select count(*) from `players` where `opengift` = 1')->field() ?? 0 ;
        if ($count <= 10000) {
          $this->account->opengift = 1;
          $gitfresult = true;
        }
      }
      $this->account->phone = $phone;
      $this->account->address = $address;
      $this->account->realname = $realname;
      return $this->okReturn([
        'gitfresult' => $gitfresult,
        'update' => boolval($this->account->update())
      ]);
    }
    return $this->okReturn([
      'phone' => $this->account->phone,
      'address' => $this->account->address,
      'realname' => $this->account->realname,
    ]);
  }

  public function infoAction()
  {
    if ($this->req->isPost()) {
      $city = $this->req->getPostTrim('city');
      $province = $this->req->getPostTrim('province');
      $country = $this->req->getPostTrim('country');
      $headimgurl = $this->req->getPostTrim('headimgurl');
      $nickname = $this->req->getPostTrim('nickname');
      if (hasEmpty([$headimgurl, $nickname])) {
        return $this->errorReturn('参数错误！！');
      }
      $this->account->city = $city;
      $this->account->province = $province;
      $this->account->country = $country;
      $this->account->headimgurl = $headimgurl;
      $this->account->nickname = $nickname;
      return $this->okReturn(boolval($this->account->update()));
    }
    return $this->okReturn([
      'newchildren' => boolval($this->getModel('mysql')->query('update `players` set `isnotice` = 1 where `parent_id` = ?', [
        $this->account->player_id
      ])->affectedRows()),
      'city' => $this->account->city,
      'province' => $this->account->province,
      'country' => $this->account->country,
    ]);
  }

  public function storeAction()
  {
    if ($player = $this->getModel('player')->getPlayer($this->req->getQueryTrim('player_id'))) {
      $store = $player->hasStore() ? $player->getStore() : false;
      if ($player->player_id != $this->account->player_id) {
        $player->visitorTo($this->account->player_id) ;
      }
      $this->account->like($player->player_id, true);
      return $this->okReturn([
        'store' => $store ? [
          'store_id' => $store->store_id,
          'monkey_appear' => boolval($store->monkey_appear),
          'items' => $store->items,
          'data' => $store->data,
          'created' => $store->created
        ] : false ,
        'islike' => $this->account->isLike($player->player_id),
        'player' => $this->__formatPlayer($player),
        'upitems' => $store ? count($store->getItems()): 0
      ]);
    }
    return $this->errorReturn('玩家不存在');
  }

  public function drivemonkeAction()
  {
    $storeModel = $this->getModel('store');
    $playerModel = $this->getModel('player');
    $store = $playerModel->getStore($this->req->getPostTrim('store_id'));
    if (!$store) { return $this->errorReturn( '该店铺不存在！！');}
    if ($store->store_id == $this->account->player_id) { return $this->errorReturn( '不能驱除自己的猴子！！'); }
    if (!$store->monkey_appear) { return $this->errorReturn( '该店铺未出现猴子！！');}
    if ($driveResult = $store->disappearMonkey()) {
      $hudongResult = $this->account->hudong('祛除猴子', "帮助店铺[{$store->nickname}]祛除猴子");
      return $this->okReturn(['flowers' => $hudongResult ? intval('0' . $this->getModel('config')->get('flowers.hudong', 5)) : 0]);
    } else {
      return $this->errorReturn( '驱除猴子失败，请重试！！');
    }
  }

  public function flowerRecordAction()
  {
    $page = max(intval($this->req->getQueryTrim('page', 1)), 1);
    $rows = intval($this->req->getQueryTrim('rows', 15));
    if (!($player = $this->getModel('player')->getPlayer($this->req->getQueryTrim('player_id')))) {
      $player = $this->account;
    }
    $list = $player->getFlowerLogsList([], $page, $rows);
    foreach ($list as $log) {
      $log->nflowers = intval($log->nflowers);
      $log->flowers = intval($log->flowers);
      $log->oflowers = intval($log->oflowers);
    }
    return $this->okReturn(['list' => $list, 'player' => $this->__formatPlayer($player)]);
  }

  public function luckydrawAction()
  {
    if (!$this->account->allowLuckydraw(date('Ymd', REQUEST_TIME), $error)) {
      return $this->errorReturn($error ?? '您今日已经投过鲜花到许愿池中');
    }
    $result = $this->account->joinLuckydraw($error);
    if ($error) { return $this->errorReturn($error); }
    return $this->okReturn(boolval($result));
  }

  public function likeAction()
  {
    $player_id = $this->req->getPostTrim('player_id');
    $friend = $this->getModel('player')->getPlayer($player_id);
    if (!$friend) { return $this->errorReturn('玩家不存在'); }
    $likeResult = boolval($this->account->like($player_id));
    if ($likeResult) {
      $this->account->hudong('点赞', "给[{$friend->nickname}]点赞");
    }
    return $this->okReturn($likeResult);
  }

  public function childrenFlowersAction()
  {
    $page = max(intval($this->req->getQueryTrim('page', 1)), 1);
    $rows = intval($this->req->getQueryTrim('rows', 15));
    return $this->okReturn($this->account->getChildrenFlowers([
      'status' => 0
    ], $page, $rows));
  }

  public function reapChildrenFlowersAction()
  {
    $flower = intval($this->account->reapChildrenFlowers());
    if ($flower) {
      return $this->okReturn($flower);
    }
    return $this->errorReturn('您今天已經領取過了，明天再來吧');
  }

}